package com.mochat.mochat.controller;

import com.alibaba.fastjson.JSONObject;
import com.mochat.mochat.common.util.HttpClientUtil;
import com.mochat.mochat.common.util.WXAuthUtil;
import com.mochat.mochat.service.impl.IContactService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;

@Controller
@RequestMapping("/mp")
public class WechatController {
    @Autowired
    private IContactService contactService;
    @GetMapping("wxlogin")
    public String wxLogin(){
        String url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ WXAuthUtil.APPID
                + "&redirect_uri="+ URLEncoder.encode("https://api6.faracat.com/mp/callBack") //这个是我们回调的地址 在这里进行出来获取到用户的心
                + "&response_type=code"
                + "&scope=snsapi_userinfo"
                + "&state=123#wechat_redirect";
        return "redirect:"+url;
    }
    @GetMapping("callBack")
    public String callBack(HttpServletRequest req){
        String code =req.getParameter("code");
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+WXAuthUtil.APPID
                + "&secret="+WXAuthUtil.APPSECRET
                + "&code="+code
                + "&grant_type=authorization_code";
        String response = HttpClientUtil.doGet(url);
        JSONObject jsonObject = JSONObject.parseObject(response);
        String openid = jsonObject.getString("openid");
        String access_token = jsonObject.getString("access_token");
        String refresh_token = jsonObject.getString("refresh_token");
        String chickUrl="https://api.weixin.qq.com/sns/auth?access_token="+access_token+"&openid="+openid;
        String checkRes = HttpClientUtil.doGet(chickUrl);
        JSONObject chickuserInfo = JSONObject.parseObject(checkRes);
        if(!"0".equals(chickuserInfo.getString("errcode"))){
            //第三步刷新access_token(刷新access_token接口)
            String refreshTokenUrl="https://api.weixin.qq.com/sns/oauth2/refresh_token?appid="+openid+"&grant_type=refresh_token&refresh_token="+refresh_token;
            String refreshRes = HttpClientUtil.doGet(refreshTokenUrl);
            JSONObject refreshInfo = JSONObject.parseObject(refreshRes);
            access_token=refreshInfo.getString("access_token");
        }
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token
                + "&openid="+openid
                + "&lang=zh_CN";
        String userInfoRes = HttpClientUtil.doGet(infoUrl);
        JSONObject userInfo = JSONObject.parseObject(userInfoRes);

        //contactService.insertContact()
        return "";
    }
}
